package com.zscat.mallplus.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zscat.mallplus.dms.service.IQsgStoreService;
import com.zscat.mallplus.qsg.QsgStore;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.MeituanUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 美团session的刷新接口
 */
@RestController
@Api(tags = "MeituanSessionApi", description = "美团session接口")
@RequestMapping("/api/meituansession")
@Slf4j
public class MeituanSessionApi {

    @Autowired
    private IQsgStoreService storeService;

    /**
     * 刷新所有店铺美团session
     *
     * @return
     */
    @ApiOperation(value = "美团授权回调接口")
    @RequestMapping(value = "/freshMeituanSession", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult freshMeituanSession() {
        log.info("开始执行美团token刷新任务");
        long startTime = System.currentTimeMillis();
        QueryWrapper qw = new QueryWrapper();
        qw.isNotNull("open_shop_uuid");
        List<QsgStore> stores = storeService.list(qw);
        for (QsgStore store : stores) {
            String meituanAppId = store.getMeituanAppid();
            String meituanAppSecret = store.getMeituanAppsecret();
            String meituanRefreshSession = store.getMeituanRefreshSession();
            int remainFreshCount = store.getRemainRefreshCount().intValue();
            if(com.jpay.util.StringUtils.isBlank(meituanRefreshSession)){
                log.info("店铺:{}没授权.",store.getName());
                continue;
            }
            //如果存在刷新session并且剩余刷新次数为0
            if(com.jpay.util.StringUtils.isNotBlank(store.getMeituanRefreshSession()) && remainFreshCount == 0){
                log.info("店铺:{}刷新次数用完,请重新授权.",store.getName());
                continue;
            }
            try {
                String tokenContent = new MeituanUtil().refreshToken(meituanAppId, meituanAppSecret, meituanRefreshSession);
                JSONObject token = JSONObject.parseObject(tokenContent);
                log.info("美团token:{}", JSON.toJSONString(token));
                if (token.getIntValue("code") == 200) {
                    String session = token.getString("access_token");
                    String refreshToken = token.getString("refresh_token");
                    int remainRefreshCount = token.getIntValue("remain_refresh_count");
                    store.setMeituanSession(session);
                    store.setMeituanRefreshSession(refreshToken);
                    store.setRemainRefreshCount(remainRefreshCount);
                    store.setMeituanRefreshTime(new Date());
                    storeService.updateById(store);
                }
            } catch (IOException e) {
                log.error("获取美团token失败.异常:{}",e.getMessage());
            }
        }
        log.info("执行完成美团token刷新任务.耗时:{}",(System.currentTimeMillis()-startTime));
        return new CommonResult().success("刷新美团session成功.",null);
    }
}
